<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-09-14
 * @Time: 14:56
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： LiveMakeRemind.php
 */
namespace app\admin\command;

use app\common\model\SysConfiguration;
use app\common\model\UserNoticeMessage;
use library\JPushZDY;
use library\ServerAPI;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

/**
 * 定时任务
 *
 * @author zhengkai
 *
 * Class LiveMakeRemind
 * @package app\admin\command
 */
class LiveMakeRemind extends Command {
    /**
     * 直播预约节目开播提醒
     * 命令：php think liveRemind
     */
    protected function configure()
    {
        $this->setName('liveRemind')->setDescription('直播节目直播开始前15分钟预约提醒');
    }

    private $template = '您预约的直播——%s将于15分钟后开播，请及时登录APP进入直播间观看。客服电话：%s。';
    protected function execute(Input $input, Output $output) {

        Db::table('user_live_subscribe')
            ->alias('uls')
            ->join('users u', 'uls.userid=u.id', 'LEFT')
            ->join('live l', 'uls.live_id=l.id', 'LEFT')
            ->where('uls.valid', 'true')
            ->field('
                uls.id as subscrib_id, 
                uls.subscribe_time, 
                u.id as user_id, 
                u.mobile as user_mobile, 
                l.title as live_title, 
                l.status as live_status,
                l.live_date,
                l.start_time as live_start_time
            ')
            ->chunk(100, function($query){
            foreach ($query as $key=>$val) {
                //直播开始时间
                $live_start_time = strtotime(date('Y-m-d H:i:s', strtotime($val['live_start_time'])));
                //计算直播开始时间与当前时间的时间差
                $diff_time = floor((strtotime($live_start_time)-time())%86400/60);

                if ($diff_time<=15) {
                    // 自定义消息内容
                    $serviceTel = SysConfiguration::getServiceTel(); // 客服电话
                    $text = sprintf($this->template, $val['live_title'], $serviceTel);

                    // 极光消息推送
                    JPushZDY::pushUsers([$val['user_id']], $text);
                    // 发送提醒短信
//                    ServerAPI::getInstance()->sendMessage(ServerAPI::TEMPLATE_LIVE_OPEN_REMIND, [$val['user_mobile']], [$val['live_title'], $serviceTel]);
                    // 创建站内消息
                    UserNoticeMessage::addMsg($val['user_id'],'直播消息', $text, UserNoticeMessage::MESSAGE_TYPE_SYSTEM);
                }
            }
            return false;
        }, 'live_start_time asc, uls.id');
    }
}